package com.cdu.supermarket.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdu.supermarket.common.redis.service.RedisTemplateService;
import com.cdu.supermarket.entity.domain.*;
import com.cdu.supermarket.entity.query.QueryExchangePointProductsRecords;
import com.cdu.supermarket.mapper.ExchangePointProductsMapper;
import com.cdu.supermarket.service.IExchangePointProductsService;
import com.cdu.supermarket.service.IGoodsService;
import com.cdu.supermarket.service.IMemberService;
import com.cdu.supermarket.service.IPointProductsService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ExchangePointProductsServiceImpl extends ServiceImpl<ExchangePointProductsMapper, ExchangePointProducts> implements IExchangePointProductsService {

    @Resource
    private IMemberService memberService;

    @Resource
    private IPointProductsService pointProductsService;

    @Resource
    private RedisTemplateService redisTemplateService;

    @Resource
    private IGoodsService goodsService;
    //会员积分商品查询
    @Override
    public List<Map<String, Object>> queryPointProductBymemberId(Long memberId) {
        //获取会员信息
        Member member = memberService.getById(memberId);
        //构建查询条件
        QueryWrapper<PointProducts> pointProductsQueryWrapper = new QueryWrapper<PointProducts>();
        if (memberId == null) {
            //如果未指定会员，显示所有积分商品
            pointProductsQueryWrapper.gt("integral", 0L);
        } else {
            // 如果指定会员，只显示积分足够的商品
            pointProductsQueryWrapper.le("integral", member.getIntegral());
        }
        //查询积分商品
        List<PointProducts> list = pointProductsService.list(pointProductsQueryWrapper);
        List<Map<String, Object>> mapArrayList = new ArrayList<>();
        for (PointProducts pointProducts : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", pointProducts.getGoodsId());
            map.put("name", pointProducts.getGoodsName());
            mapArrayList.add(map);
        }
        return mapArrayList;
    }
    //根据商品ID查询对应的积分商品信息
    @Override
    public PointProducts queryPointProductByGoodsId(Long goodsId) {
        PointProducts pointProducts = pointProductsService.getOne(new QueryWrapper<PointProducts>().eq(goodsId != null, "goods_id", goodsId));
        return pointProducts;
    }
    //保存积分兑换记录
    @Override
    public void saveExchangePointProductRecords(ExchangePointProducts exchangePointProducts, String token) {
        //获取当前登录员工
        Employee employee = JSONObject.parseObject(redisTemplateService.getCacheObject(token), Employee.class);
        //设置兑换记录信息
        exchangePointProducts.setCn(IdWorker.getIdStr());//使用MyBatis-Plus的IdWorker生成唯一订单号
        exchangePointProducts.setUpdateby(employee.getNickName());
        exchangePointProducts.setUpdateId(employee.getId());
        exchangePointProducts.setUpdateTime(new Date());
        exchangePointProducts.setState(ExchangePointProducts.STATE_NORMAL);
        /*修改会员的积分*/
        Member member = memberService.getById(exchangePointProducts.getMemberId());//会员ID查询信息
        member.setIntegral(member.getIntegral() - exchangePointProducts.getIntegral());//扣除积分
        memberService.updateById(member);//更新会员积分
        super.save(exchangePointProducts);

    }
    //查询所有有过积分兑换记录的会员手机号
    @Override
    public List<Map<String, Object>> queryOptionsMemberPhone() {
        QueryWrapper<ExchangePointProducts> wrapper = new QueryWrapper<ExchangePointProducts>()
                .select("member_id")// 只查询会员ID字段
                .eq("state", ExchangePointProducts.STATE_NORMAL)// 只查询正常状态的记录
                .groupBy("member_id");// 按会员ID分组，去重
        List<ExchangePointProducts> list = super.list(wrapper);
        //提取会员ID列表
        List<Long> memberIds = new ArrayList<>();
        for (ExchangePointProducts exchangePointProducts : list) {//遍历查询结果，提取所有会员ID
            memberIds.add(exchangePointProducts.getMemberId());
        }
        //空值查询
        if (memberIds==null || memberIds.size()<=0){
            return null;
        }
        List<Member> members = memberService.listByIds(memberIds);//批量查询会员信息
        List<Map<String, Object>> vos = new ArrayList<>();
        for (Member member : members) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", member.getId());
            map.put("name", member.getPhone());
            vos.add(map);
        }

        return vos;
    }
    //软删除积分兑换记录
    @Override
    public void delExchangePointProducts(String cn) {
        UpdateWrapper<ExchangePointProducts> wrapper = new UpdateWrapper<ExchangePointProducts>()
                .set("state", ExchangePointProducts.STATE_DEL)// 设置状态为删除
                .eq("cn", cn);// 根据订单号匹配记录
        super.update(wrapper);
    }
    //分页查询积分兑换记录，支持多条件筛选，并填充关联的会员和商品信息
    @Override
    public Page<ExchangePointProducts> queryPageByQoExchangePointProducts(QueryExchangePointProductsRecords qo) {
        Page<ExchangePointProducts> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        QueryWrapper<ExchangePointProducts> queryWrapper = new QueryWrapper<ExchangePointProducts>()
                .eq("state", ExchangePointProducts.STATE_NORMAL)
                .eq(qo.getMemberId() != null, "member_id", qo.getMemberId())
                .ge(StringUtils.hasText(qo.getStartTime()), "update_time", qo.getStartTime())
                .le(StringUtils.hasText(qo.getEndTime()), "update_time", qo.getEndTime())
                .likeRight(StringUtils.hasText(qo.getCn()), "cn", qo.getCn());//订单号查询
        super.page(page, queryWrapper);
        //关联数据填充
        for (ExchangePointProducts record : page.getRecords()) {
            // 填充会员信息
            Member member = memberService.getById(record.getMemberId());
            record.setMemberPhone(member.getPhone());
            // 填充商品信息
            Goods goods = goodsService.getById(record.getGoodsId());
            record.setGoodsCoverUrl(goods.getCoverUrl());
            record.setGoodsName(goods.getName());
        }
        return page;
    }
    //查询所有正常状态的积分商品
    @Override
    public List<Map<String, Object>> queryOptionsPointProducts() {
        QueryWrapper<PointProducts> wrapper = new QueryWrapper<PointProducts>()
                .eq("state", PointProducts.STATE_NORMAL);
        List<PointProducts> list = pointProductsService.list(wrapper);
        List<Map<String, Object>> vos = new ArrayList<>();
        for (PointProducts pointProducts : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", pointProducts.getGoodsId());
            map.put("name", pointProducts.getGoodsName());
            vos.add(map);
        }
        return vos;
    }
    //查询所有正常状态的会员
    @Override
    public List<Map<String, Object>> queryOptionsMember() {
        List<Map<String, Object>> vos = new ArrayList<>();
        QueryWrapper<Member> wrapper = new QueryWrapper<Member>()
                .groupBy("id")
                .eq("state", Member.STATE_NORMAL);
        List<Member> list = memberService.list(wrapper);
        for (Member member : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", member.getId());
            map.put("name", member.getPhone());
            vos.add(map);
        }
        return vos;
    }
    //根据商品ID查询有足够积分兑换该商品的会员列表
    @Override
    public List<Map<String, Object>> queryMemberByGoodsId(Long goodsId) {
        List<Member> members = new ArrayList<>();
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<Member>();
        memberQueryWrapper.eq("state", Member.STATE_NORMAL);
        if (goodsId != null) {
            PointProducts pointProducts = pointProductsService.getOne(new QueryWrapper<PointProducts>()
                    .eq("goods_id", goodsId)
                    .eq("state", PointProducts.STATE_NORMAL));
            memberQueryWrapper.ge("integral", pointProducts.getIntegral());
        } else {
            memberQueryWrapper.gt("integral", 0);
        }
        members = memberService.list(memberQueryWrapper);
        List<Map<String, Object>> vos = new ArrayList<>();
        for (Member member : members) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", member.getId());
            map.put("name", member.getPhone());
            vos.add(map);
        }
        return vos;
    }
}
